package com.jredu.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.jredu.dao.BaseDao;
import com.jredu.dao.UserDao;
import com.jredu.entity.User;

public class UserDaoImpl extends BaseDao{

	
	
	public List<User> findUsers() {
		List<User> users = new ArrayList<User>();
		StringBuilder sb = new StringBuilder();
		sb.append("select u.id,u.account,u.pwd,u.`NAME`,u.email,u.phone,u.qq,u.remark,");
		sb.append("d.id as deptNo,");
		sb.append("d.`name` as deptName,");
		sb.append("d.`desc` as deptDesc,");
		sb.append("d.pid pid,");
		sb.append("r.id as roleId,");
		sb.append("r.`name` as roleName,");
		sb.append("r.`desc` as roleDesc ");
		sb.append(" from ");
		sb.append(" users u  ");
		sb.append(" LEFT JOIN depts d  ");
		sb.append(" on u.dept = d.id ");
		sb.append(" LEFT JOIN roles r ");
		sb.append(" on u.role = r.id order by u.id");
		ResultSet rs = this.executeQuery(sb.toString(), null);
		try {
			while(rs.next()){
				User user = new User(
						rs.getInt("id"),
						rs.getString("account"),
						rs.getString("pwd"),
						rs.getString("name"),
						null,
						null, 
						rs.getString("phone"),
						rs.getString("qq"),
						rs.getString("remark"));
//				Dept dept = new Dept(
//						rs.getInt("deptNo"), 
//						rs.getString("deptName"),
//						rs.getInt("pid"),
//						rs.getString("deptDesc"));
//				Role role = new Role(
//						rs.getInt("roleId"),
//						rs.getString("roleName"), 
//						rs.getString("roleDesc"));
//				user.setDept(dept);
//				user.setRole(role);
				users.add(user);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			this.close();
		}
		return users;
	}

	public User login(String account, String pwd) {
		String query="select * from users where account = ? and pwd = ?";
		List<Object> params = new ArrayList<Object>();
		params.add(account);
		params.add(pwd);
		ResultSet rs = this.executeQuery(query, params);
		User user = null;
		try {
			if(rs.next()){
				user = new User(
						rs.getInt("id"),
						rs.getString("account"),
						rs.getString("pwd"),
						rs.getString("name"),
						rs.getString("dept"),
						rs.getString("role"), 
						rs.getString("phone"),
						rs.getString("qq"),
						rs.getString("remark"));

			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			this.close();
		}
		return user;
	}

}
